<?php

if(!isset($_REQUEST['rs']) && $_SESSION['saccount']!=123997){
include 'prod_sale_pro.html';  
exit;
}

include 'common/autoload.php';
include 'common/header.html';
include 'common/left.html';
include 'common/page.php';
include 'common/area.inc.php';
include 'common/Prod_Common.php';
// 现场支付不允许转分销
$soap = SoapInit::GetSoapInside();
$sale = new \pft\Prod\Sale($GLOBALS['le'], $_SESSION['sid']);

$pid_arr = array();//产品ID
$sid_arr = array();//供应商id
// 二手销售数据
$sql_get = <<<SQL
SELECT e.id,e.fid,e.pid,e.sid,e.sourceid,e.lvl,e.status,e.aids,e.active
FROM pft_p_apply_evolute e INNER JOIN uu_products p ON p.id=e.pid
WHERE fid={$_SESSION['sid']}
AND p.apply_limit=1 AND p.p_status IN(0,2,3,4,5) AND e.status=0
SQL;
if(isset($_GET['pid'])) $sql_get .= " AND t.pid={$_GET['pid']}";
$GLOBALS['le']->query($sql_get);
$edatas = $epid_arr = $sid_pid = $pid_arr = array();
while($r=$GLOBALS['le']->fetch_assoc()) {
    $edatas[]   = $r;
    $epid_arr[] = $r['pid'];
    $sid_arr[]  = $r['sid'];
    $aid_arr[]  = $r['aids'];
    $sid_pid[]  = $r['sid'] . '_' . $r['pid'];
}

// 一手直接供应可购买的产品 pid
$pid_arr = $sale->GetProdsid();

// 没有一手的并且二手以上的有
if(!count($pid_arr) && count($epid_arr)>0) {
    $pid_arr = $epid_arr;
}

if(!count($pid_arr)) {
    echo '<script>alert("您暂无可供应产品");history.go(-1);</script>';
    exit;
}
// 一手供应的产品信息
$pids = implode(',',$pid_arr);
$pids = str_replace(',,',',',$pids);//某些错误的记录里会导致两个逗号中间是空的 
$sql_apply_did = "SELECT id,apply_did FROM uu_products WHERE id IN($pids) AND apply_limit=1 AND p_status IN(0,2,3,4,5)";
$GLOBALS['le']->query($sql_apply_did);
while($list = $GLOBALS['le']->fetch_assoc()){
    $prod_init_prod[] = array(
        'fid'=>$_SESSION['sid'],
        'pid'=>$list['id'],
        'sid'=>$list['apply_did'],
        'aids'=>$list['apply_did'],
        'sourceid'=>$list['apply_did'],
        'lvl'=>0,
        'status'=>-1,
        'active'=>0,
    );
}

// print_r($prod_init_prod);
// exit;

// 合并一手供应及多级供应的产品 PID
$pid_str = implode(',',$pid_arr);
$pid_arr = array_merge($epid_arr, explode(',', $pid_str));
$uniq_pid = $pid_arr = array_unique($pid_arr);

// print_r($uniq_pid);
// exit;
if( count($edatas)>0 && $prod_init_prod ) {
    foreach($prod_init_prod as $key=>$val) {
        $nk = $val['sid'].'_'.$val['pid']; // 一手供应标志
        if(false!==array_search($nk,$sid_pid ) ) { // 一手供应的产品是否有权限销售
            unset($prod_init_prod[$key]);
        }
    }
    $prod_init_prod = array_merge($edatas, $prod_init_prod);
}elseif(count($edatas)>0){
	$prod_init_prod = $edatas;
}

// echo "<pre>";
// print_r($prod_init_prod);
// exit;


// 获取唯一的景区门票信息
$pid_str = implode(',', $uniq_pid);
$pid_str = str_replace(',,',',',$pid_str);
$sql = <<<SQL
SELECT t.id as ticket_id, t.landid, l.title as ltitle,t.title as ttitle,
t.pid, t.pay FROM uu_jq_ticket t LEFT JOIN uu_land l ON l.id=t.landid
 WHERE t.pid IN($pid_str)
SQL;
//echo $sql;
$GLOBALS['le']->query($sql);
$data = array();
while($l = $GLOBALS['le']->fetch_assoc()) {
    $data[$l['pid']] = $l;
}
// print_r($data);

$sale_data = array();
$sort_pid = array();
$today = date('Y-m-d');
// 获取上级配置价格
$account = $_SESSION['saccount'];

//允许转分销现在支付的供应商分组
$allow_sale_group = array(
    4=>'yd',
    5=>'gly',
);


$get_account_group = <<<SQL
SELECT group_id FROM pft_member WHERE id={$_SESSION['memberID']} LIMIT 1
SQL;
$GLOBALS['le']->query($get_account_group);
$GLOBALS['le']->fetch_assoc();
$group_id = $GLOBALS['le']->f('group_id');

if(count($prod_init_prod)){
	foreach($prod_init_prod as $ed){
		if($ed['pid']=='11520')//这个产品是青岛琅邪台 先行同步过来的 用取价钱的接口会报错
			continue;
		$sid_arr[]  = $ed['sid'];
		// $fprice = $soap->get_Dynamic_Price_Merge($ed['pid'], $today, 1, '', '', 0);//当日供应价
		// $uprice = $soap->get_Dynamic_Price_Merge($ed['pid'], $today, 1, '', '', 1);//当日零售价
		$xml = $soap->Dynamic_Price_And_Storage($account,$ed['pid'],$today,1,0,0,$ed['sid']);
		if($xml==105 || $xml==1065){
			$xml = $soap->Dynamic_Price_And_Storage($account,$ed['pid'],$today,2,0,0,$ed['sid']);
			if($xml==105 || $xml==1065) continue; // 获取不到说明没有权限销售
		}
		$object = simplexml_load_string($xml);
		$fprice = (string)$object->Rec->UUsprice/100;
		// $fprice = 100;
		
		$xml = $soap->Dynamic_Price_And_Storage($account,$ed['pid'],$today,1,1,0,$ed['sid']);
		if($xml==105 || $xml==1065) {
			$xml = $soap->Dynamic_Price_And_Storage($account,$ed['pid'],$today,2,1,0,$ed['sid']);
			if($xml==105 || $xml==1065) continue; // 获取不到说明没有权限销售
		}
		$object = simplexml_load_string($xml);
		$uprice = (string)$object->Rec->UUsprice/100;
		// $uprice = 100;
		
		$sid = $ed['lvl'] == 0 || $ed['lvl']==1  ? 0 : $ed['sid'];
        //默认过滤现场支付的产品，特殊分组的除外
		if (array_key_exists($group_id, $allow_sale_group)
            || $data[$ed['pid']]['pay']<>0){
			$sale_data[$ed['pid']][] = array(
				'sid' => $ed['sid'],
				'sourceid' => $ed['sourceid'],
				'eid' => $ed['id'],
				'lvl' => $ed['lvl'],
				'aids' => $ed['aids'],
				'status' => $ed['status'],
				'active' => $ed['active'],
				'applyer_id' => $ed['sid'],
				'fprice' => $fprice,
				'uprice'=> $uprice,
				'data' => $data[$ed['pid']]
			);
		}
	}
}
// if($_SESSION['sid']==6610){
	// print_r($sale_data);
// }
// print_r($sale_data);
// exit;
//获取供应商的名称
if (count($sid_arr)) {
    $sid_str = implode(',', array_unique($sid_arr));
    $sql_dname = "SELECT id,dname FROM pft_member WHERE id IN($sid_str)";
    $GLOBALS['le']->query($sql_dname);
    $dnames = array();
    while($dn = $GLOBALS['le']->fetch_assoc()) {
        $dnames[$dn['id']] = $dn['dname'];
    }
}
?>
<style>
.none_a{display:none;}
</style>
<link rel="stylesheet" type="text/css" href="css/aliceui.min.css"/>
<link rel="stylesheet" type="text/css" href="css/c_common.css"/>
<link rel="stylesheet" type="text/css" href="js/dataTable/jquery.dataTables.min.css">
<script type="text/javascript" charset="utf8" src="js/dataTable/jquery.dataTables.min.js"></script>
<div class="clay">
    <div class="content">
        <h3 class="mc_title">
            <span class="mctit_1 mctit_3"><a href="prodlists.html" class="mctit_2 mctit_4">自供应产品</a></span>
            <span class="mctit_1"><span class="mctit_2">转分销产品</span></span>
        </h3>
        <div id="prod_sale_tiptext" class="ui-tiptext-container ui-tiptext-container-warning">
            <p class="ui-tiptext">
                您可以将其他供应商分销给您的产品再分销给您的其他分销商。
                <span style="color: red"><a href="prod_sale_pro.html">返回新版</a></span>
            </p>
            <p class="ui-tiptext ui-tiptext-warning">
               若同一个产品有多个供应商，请勾选一个供应商保存后再配置价格。
            </p>
			<?if(isset($_SESSION['alliance'])):?>
			<p class="ui-tiptext ui-tiptext-warning">
               若您是联盟账号，无法为每个分销商分配价格，即无法显示“分销价格”按钮
            </p>
			<?endif;?>
        </div>
        <iframe src="about:blank" style="height: 0;width: 0;display: none;" id="hideFrame" name="hideFrame" frameborder="0"></iframe>
        <div class="ui-table-container">
            <table id="tbl_evlt" class="ui-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th style="width:280px;" >产品名称</th>
                        <?if($_SESSION['saccount']==123997){//云游
                            $px =
        file_get_contents('/var/www/html/new/d/module/zax/caiyoumeng/px_config.txt');
                            $px = json_decode($px,true);
                        ?>
                        <th style="width:45px;">热门度</th>
                        <?}?>
                        <th style="width:39px;">供货价</th>
                        <th style="width:39px;">零售价</th>
                        <th>供应商</th>
                        <th>选择</th>
                    </tr>
                </thead>
				<tbody>
                <?foreach($sale_data as $pid=>$lists):?>
                    <?foreach($lists as $list):?>
                    <?//if($list['lvl']>2):continue;?>
           
                    <tr>
                        <td title="账户ID|景区ID|门票ID"><?=$_SESSION['sid']?>|<?=$list['data']['landid']?>|<?=$list['data']['ticket_id']?></td>
                        <td><?=$list['data']['ltitle'].'-'.$list['data']['ttitle']?></td>
                        <?if($_SESSION['saccount']==123997){//云游?>
                        <td><input style="width:45px;"
                    data-lid="<?=$list['data']['landid']?>"   class="px"
                   value="<?=$px[$list['data']['landid']]//排序?>"/></td>
                        <?}?>
                        <td><?=$list['fprice']?></td>
                        <td><?=$list['uprice']?></td>
                        <td data-aid="<?=$list['applyer_id']?>"><?=$dnames[$list['applyer_id']]?></td>
                        <td>
						
                            <input class="chkOnlyOne" data_name="<?=$list['data']['ltitle'].'-'.$list['data']['ttitle']?>" data_pid="<?=$list['data']['pid']?>" data_lvl="<?=$list['lvl']?>" data_all="<?=$_SESSION['alliance']?>" data_active="<?=$list['active']?>" data_sid="<?=$list['sid']?>" data_aids="<?=$list['aids']?>"type="checkbox"
                                   value="<?=$list['sourceid'].'|'.$list['aids'].'|'.$list['eid'].'|'.$list['sid']?>"
                                   name="evlt_<?=$list['data']['pid']?>"
                           
                                   />
								
								<a class="none_a" target="_blank" href="adjusting.html?pid=<?=$list['data']['pid']?>&sid=<?=$list['sid']?>&lvl=<?=$list['lvl']?>&aids=<?=$list['aids']?>">
                                分销价格</a>
							
                        </td>
                    </tr>
                    <?endforeach;?>
<!--                    <tr>-->
<!--                        <td colspan="6"> &nbsp; </td>-->
<!--                        <td>-->
<!--                            <input type="submit" class="ui-button ui-button-sorange" value="保存">-->
<!--                        </td>-->
<!--                    </tr>-->
                  
                <?endforeach;?>
				  </tbody>
            </table>
<script>
$(document).ready(function() {
    $('#tbl_evlt').dataTable( {
        "oLanguage": {
            "sLengthMenu": "每页显示 _MENU_ 条记录",
            "sZeroRecords": "抱歉， 没有找到",
            "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
            "sInfoEmpty": "没有数据",
            "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "前一页",
                "sNext": "后一页",
                "sLast": "尾页"
            },
            "sZeroRecords": "没有检索到数据",
            "sProcessing": "<img src='./loading.gif' />"
        }
    });
	
	//var data_active = $(".chkOnlyOne").attr('data_active');
	//console.log(data_active);
	
	
	
	
	
	
	
});
$(".chkOnlyOne").each(function(i){ 
		var active = $(this).attr('data_active'); 
		var all = $(this).attr('data_all'); 
		var lvl = $(this).attr('data_lvl'); 
		var name = $(this).attr('data_name'); 
		if(active=='1'){
		
		$(this).attr('checked','checked');
		 if(!(typeof(all) == "undefined")&&lvl<3) {
		 //alert(name);
		 $(this).next('a').css("display","block");
		 }
		 else{}
		}
		else{
		$(this).removeAttr('checked');
		}
	}); 
</script>
        </div>
    </div>
</div>
<script>

    $("table#tbl_evlt").on('click', '.chkOnlyOne', function(){
		var lvl = $(this).attr('data_lvl');
		var data_all = $(this).attr('data_all');
		var data_pid = $(this).attr('data_pid');
		var data_sid = $(this).attr('data_sid');
		var data_aids = $(this).attr('data_aids');
        var tname = $(this).attr('name');
        var data = {
            action : 'ProdEvolute',
            pid : $(this).attr('data_pid'),
            info: $(this).val()
        };

        if($(this).attr('checked')) {
            if(!confirm('您确定要变更该产品的供应商吗？')) {
                return false;
            }
           data['dtype'] = 1;
		   if(lvl<3){
				$(this).attr('checked','checked');
				$(this).next('a').css("display","block");
			 }
			 else{}
        }
        else {
            //if($(this).attr('data-active')!=1) {
           //    return false;
           //}
            if(!confirm('您确定要取消供应该产品吗？')) {
                return false;
           }
		   $('input[name="'+tname+'"]').removeAttr('checked');
			$(this).next('a').css("display","none");
            data['dtype'] = 0;
            //如果不是当前配置项不用提交

        }
		//var avtive_d  = $(this).attr('data-active');
		//alert(avtive_d)
        $.post('call/jh_prod.php',data, function(res){
            if(res.status=='ok') { 
				if(res.active=="0"){
					alert('取消成功！');
					$('input[name="'+tname+'"]').removeAttr('checked');
					 $(this).next('a').css("display","none");
				}
				else{
					alert('操作成功！');
					$(this).attr('checked','checked');
					$(this).next('a').css("display","block");
				}
				//alert(res.active)
			//$(this).attr("data-active",res.active);
			//$('input[data-active='+avtive_d+']').val(res.active);
              
            } else {
                alert(res.msg);
            }
        },'json');
    });
    <?if($_SESSION['saccount']==123997){//云游?>
    $("table#tbl_evlt").on('change', 'input.px', function(){
        var px = $(this).val();
        var lid  = $(this).attr('data-lid');
        var data = {"lid":lid,"px":px};
        $.post('module/zax/caiyoumeng/g.php',data, function(res){
            if(res.status=='ok') {
                alert('操作成功！');
                $('input[data-lid='+lid+']').val(px);
            } else {
                alert(res.msg);
            }
        },'json');
    });
    <?}?>

</script>
<?include('common/footer.html');?>